package com.jimei.voucher.service.impl;

import java.io.IOException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.jimei.voucher.config.RabbitConfig;
import com.jimei.voucher.service.OrderReceiveService;
import com.jimei.voucher.service.OrderService;
import com.rabbitmq.client.Channel;

/**
 * 取消订单接收
 * 
 * 2018年9月17日
 */
@Service
public class OrderReceiveServiceImpl implements OrderReceiveService {
    private static Logger logger = LoggerFactory.getLogger(OrderReceiveServiceImpl.class);
    
    @Autowired
    private OrderService orderService;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    
    @RabbitListener(
            bindings=@QueueBinding(
                    value=@Queue(RabbitConfig.ORDER_CANCEL_QUEUE), 
                    exchange=@Exchange(RabbitConfig.ORDER_CANCEL_EXCHANGE), 
                    key= {RabbitConfig.DIRECT_ORDER}),
            concurrency="2")
    public void processOrder(Channel channel, Message message) {
        try {
            logger.info("processOrder {}", message);
            String pid = new String(message.getBody());
            orderService.cancelByPid(pid);
        } catch (Exception e) {
            logger.error(message.toString(), e);
        } finally {
            rabbitTemplate.send(RabbitConfig.ORDER_CANCEL_EXCHANGE, RabbitConfig.DIRECT_ORDER, message);
            try {
                channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
            } catch (IOException e) {
                logger.error(message.toString(), e);
            }
        }
    }

}
